package com.tucanstubs.android_wheresmystuff.database;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.tucanstubs.android_wheresmystuff.items.Item;
import com.tucanstubs.android_wheresmystuff.login.Admin;
import com.tucanstubs.android_wheresmystuff.login.User;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
 * This class contains all the methods associated with
 * getting adding and removing users from the database
 * @author Group 37
 * @version 2.0 4/12/2013
 */
public class UserHelper{

	private static SQLiteOpenHelper dbhelper;
	private static SQLiteDatabase database;
	
	private static final String TAG = "USERHELPER";
	/**
	 * Open a writable database instance. Also refresh the current 
	 * DatabaseOperator instance if it is null;
	 * @param context The current running Activity
	 */
	private static void open(Context context){
		dbhelper = DatabaseOperator.getInstance(context);
		database = dbhelper.getWritableDatabase();
	}
	/**
	 * Adds or updates a user in the database. If the user is already in the database
	 * update their entry with new values. If they are'nt create a new row for them 
	 * @param context The current running Activity
	 * @param newUser A new or current user coming in for creation/updation
	 */
	public static void add(Context context, User newUser){
			
			ContentValues values = new ContentValues();
			values.put(DatabaseOperator.USERNAME_COLUMN,newUser.getUserName());
			values.put(DatabaseOperator.FIRSTNAME_COLUMN,newUser.getFirstName());
			values.put(DatabaseOperator.LASTNAME_COLUMN,newUser.getLastName());
			values.put(DatabaseOperator.PASSWORD_COLUMN,newUser.getPassword());
			values.put(DatabaseOperator.LOCKED_COLUMN,newUser.getLockCount());
			values.put(DatabaseOperator.EMAIL_COLUMN,newUser.getEmail());
			values.put(DatabaseOperator.LOCKCOUNT_COLUMN,0);
			if(newUser instanceof Admin)
				values.put(DatabaseOperator.ADMIN_COLUMN,1);
			else
				values.put(DatabaseOperator.ADMIN_COLUMN,0);
			if(!contains(context,newUser.getUserName())){
				open(context);
				database.insert(DatabaseOperator.USER_TABLE_NAME,null,values);
			}else{
				open(context);
				String filter = DatabaseOperator.USERNAME_COLUMN + "=" 
				+ "'" +newUser.getUserName() + "'";
				database.update(DatabaseOperator.USER_TABLE_NAME,values,filter,null);
				database.close();
				for(Item i:newUser.getItems())
					ItemHelper.addItem(context, i, newUser);
			}
			dbhelper.close();
	}
	/**
	 * Removes the given user from the database
	 * @param context The current running Activity
	 * @param usr The user to delete
	 */
	public static void remove(Context context,User usr){
		open(context);
		database.delete(DatabaseOperator.USER_TABLE_NAME,
				DatabaseOperator.USERNAME_COLUMN + "=" + "'" 
		+ usr.getUserName() + "'" ,null);
		database.delete(DatabaseOperator.ITEM_TABLE_NAME,
				DatabaseOperator.USER_ID + "=" + "'"
		+ usr.getUserName() + "'",null);
		dbhelper.close();
	}
	/**
	 * Checks whether a given user is in the database or no
	 * @param context The current running Activity
	 * @param userName The user to lookup
	 * @return Whether or not userName exists in the database
	 */
	public static boolean contains(Context context, String userName){
		Boolean exists = UserHelper.get(context,userName) != null;
		return exists;
	}
	/**
	 * Gets a user from the database based on the user name
	 * @param context The current running activity
	 * @param userName The user to lookup
	 * @return Returns null if the user doesn't exist, returns the user if they do
	 */
	public static User get(Context context,String userName){
		open(context);
		String query = "SELECT * FROM " + DatabaseOperator.USER_TABLE_NAME 
				+ " WHERE " + DatabaseOperator.USERNAME_COLUMN + "="
				+ "'" + userName + "'";
		Cursor cursor = database.rawQuery(query,null);
		cursor.moveToFirst();
		if(cursor.getCount() != 1){
			cursor.close();
			dbhelper.close();
			return null;
		}else {
			User ret = cursorToUser(cursor);
			cursor.close();
			dbhelper.close();
			ret.setItems(ItemHelper.getItems(context,ret.getUserName()));
			return ret;
		}
		
	}
	/**
	 * Converts a cursor generated by a query to a user object
	 * @param cursor The cursor to be converted
	 * @return A user associated with the data in the cursor
	 */
	private static User cursorToUser(Cursor cursor){
		int isAdmin = cursor.getInt(7);
		User ret;
		if(isAdmin == 0){
			ret = new User(cursor.getString(0),cursor.getString(1),
					cursor.getString(2),cursor.getString(3),cursor.getString(5));
			ret.setLockCount(cursor.getInt(6));
			int locked = cursor.getInt(4);
			if(locked == 0)
				ret.setLocked(false);
			else
				ret.setLocked(true);
		}else 
			ret = new Admin(cursor.getString(0),cursor.getString(1),
					cursor.getString(2),cursor.getString(3),cursor.getString(5));
		return ret;
	}
	/**
	 * Get a list of all user names from the database
	 * @param context The current running Activity
	 * @return A list of every user name in the database
	 */
	public static List<String> getUserNames(Context context){
		open(context);
		ArrayList<String> list = new ArrayList<String>();
		String[] returnColumns = {DatabaseOperator.USERNAME_COLUMN};
		Cursor cursor = database.query(DatabaseOperator.USER_TABLE_NAME,
				returnColumns,null,null,null,null,null);
		cursor.moveToFirst();
		while(!cursor.isAfterLast()){
			list.add(cursor.getString(0));
			cursor.moveToNext();
		}
		cursor.close();
		dbhelper.close();
		return list;
	}
}
